import Vue from 'vue'
import Pinyin from 'js-pinyin'
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
Vue.filter('NumberFormat', (value) => {
  if (!value) {
    return '0'
  }
  const intPartFormat = value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') // 将整数部分逢三一断
  return intPartFormat
})

Vue.filter('dayjs', (dataStr, pattern = 'YYYY-MM-DD') => {
  return moment(dataStr).format(pattern)
})
Vue.filter('month', (dataStr, pattern = 'YYYYMM') => {
  return moment(dataStr).format(pattern)
})
Vue.filter('moment', (dataStr, pattern = 'YYYY-MM-DD HH:mm:ss') => {
  return moment(dataStr).format(pattern)
})

// 字典对应值
Vue.filter('DictLabelFilter', (value, dictData) => {
  if (!dictData) {
    return ''
  }
  const obj = {}
  dictData.forEach(item => {
    obj[item.value] = item.name
  })
  return obj[value]
})

// 字符过长 在表格中省略号显示
// Vue.filter('TableTooltip', function (value, num) {
//   let htmlContent = ""
//   if (value.length > num) {

//   } else {
//     htmlContent = `<span>${value}</span>`
//   }
//   return htmlContent;
// })

// 字节处理
// 使用 strSize = this.$options.filters.renderSize(size)
Vue.filter('renderSize', (value) => {
  if (!value || value === '0') {
    return '0 Bytes'
  }
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  let index = 0
  const srcsize = parseFloat(value)
  index = Math.floor(Math.log(srcsize) / Math.log(1024))
  let size = srcsize / Math.pow(1024, index)
  //  保留的小数位数
  size = size.toFixed(2)
  return `${size}${unitArr[index]}`
})

// 将下拉框的options按name的拼音首字母排序
Vue.filter('sortByFirstLetter', (origin) => {
  let newSortedArr = []
  if (origin && origin.length > 0) {
    // eslint-disable-next-line max-len
    newSortedArr = origin.sort((pre, next) => Pinyin.getFullChars(pre.name).localeCompare(Pinyin.getFullChars(next.name)))
  }
  return newSortedArr
})
